<?php

namespace app\common\model\company;
use app\common\model\orderdata\Goods;
use think\Model;

class ContractDetails extends Model
{
	// 设置当前模型对应的完整数据表名称
	protected $table = 'contract_details';
	protected $pk = 'Id';

	public function goodinfo()
	{
		return $this->hasOne('app\common\model\orderdata\Goods', 'GoodId', 'GoodId');
	}

	/**
	 * 创建合同详细信息
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function screate($id,$data)
	{
		if (empty($data['ContractDetails'])) {
			return sok('无需创建合同详情');
		}
		$ndata = [];
		$filed = ['GoodId','GoodName','DeductType','DeductNum','Price','Box','ObjectState','Harmful','Usage','EstimatedWeight','Limit'];

		$harmperfect = ['id'=>[],'value'=>[]];
		$nameperfect= ['id'=>[],'value'=>[]];
		//将数组整合到一起
		foreach ($data['ContractDetails'] as $key2 => $value2) {
			$ndata[$key2]['ContractId'] = $id;
			foreach ($filed as $key => $filvalue) {
				if(isset($value2[$filvalue])){
					$ndata[$key2][$filvalue] = $value2[$filvalue];
				}
			}
			//复制抵扣量至剩余抵扣量字段
			if(isset($value2['DeductNum'])){
				$ndata[$key2]['SurplusDedutNum'] = $value2['DeductNum'];
			}
			
			//完善库中的危废名称
			if(isset($value2['GoodName'])){
				$nameperfect['id'][] = $value2['GoodId'];
				$nameperfect['value'][] = $value2['GoodName'];
			}
			//完善库中的危废有害物质
			if(isset($value2['Harmful'])){
				$harmperfect['id'][] = $value2['GoodId'];
				$harmperfect['value'][] = $value2['Harmful'];
			}
		}

		//完善库中的危废名称
		if(!empty($nameperfect['value'])){
			Goods::NamePerfect($nameperfect['id'],$nameperfect['value']);
		}

		//完善库中的危废有害物质
		if(!empty($harmperfect['value'])){
			Goods::HarmfulListPerfect($harmperfect['id'],$harmperfect['value']);
		}
		$cd = new ContractDetails;
		$cd->saveAll($ndata);
		return sok('保存成功');
	}
}
